package com.rpoonolly.simpleandroidgame;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

import com.rpoonolly.simplegame.SimpleUserAction;
import com.rpoonolly.simplegame.core.InputManager;

public class AndroidInputHandler implements InputManager<SimpleUserAction>, OnTouchListener {
	private Map<SimpleUserAction, Boolean> inputStateMap;
	private Context context;
	
	private int curActionIndex = -1;
	private float lastTouchX, lastTouchY;
	
	public AndroidInputHandler(Context context) {
		this.context = context;
		inputStateMap = new ConcurrentHashMap<SimpleUserAction, Boolean>();
		for(SimpleUserAction action : SimpleUserAction.values()) {
			inputStateMap.put(action, false);
		}
	}
	
	@Override
	public boolean isActionRequested(SimpleUserAction action) {
		return inputStateMap.get(action);
	}

	@Override
	public void clearActionRequests() {
		for(SimpleUserAction action : inputStateMap.keySet()) {
			inputStateMap.put(action, false);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent e) {
		if(curActionIndex < 0) {
			curActionIndex = e.getActionIndex();
			lastTouchX = e.getX();
			lastTouchY = e.getY();
			return true;
		} else if(curActionIndex != e.getActionIndex() || e.getAction() != MotionEvent.ACTION_UP)
			return false;
		
		clearActionRequests();
		float dx = lastTouchX - e.getX();
		float dy = lastTouchY - e.getY();
		curActionIndex = -1;
		
		SimpleUserAction action;
		if (Math.abs(dx) > Math.abs(dy))
			action = (dx < 0) ? SimpleUserAction.PLAYER_MOVE_RIGHT : SimpleUserAction.PLAYER_MOVE_LEFT;
		else
			action = (dy < 0) ? SimpleUserAction.PLAYER_MOVE_DOWN : SimpleUserAction.PLAYER_MOVE_UP;	
		
		inputStateMap.put(action, true);
		Toast.makeText(context, "action: " + action.name(), Toast.LENGTH_SHORT).show();
			
		return true;
	}
}
